import { memo, useEffect } from "react";
import { Button, Col, Drawer, Form, Input, InputNumber, message, Row, Select, Space, Spin } from "antd";
import { ProductType, propsType } from "../../config";
import TextArea from "antd/es/input/TextArea";
import { useFetch_commitProduct, useFetch_getProductInfo } from "../../../../service/product";
import UploadV2 from "../../../../baseUI/uploadV2";
import { parseInt } from "lodash-es";
import { product_arr } from "../../../../constant";

const Edit = memo((props: propsType) => {
  const { id, close, open } = props;

  const [form] = Form.useForm();
  const [edit, editLoading] = useFetch_commitProduct();
  const [getProductInfo, loading] = useFetch_getProductInfo();
  useEffect(() => {
    if (id) {
      getProductInfo(id).then((res: any) => {
        const newData = {
          ...res,
          cover: [{ url: res.cover as string }],
          bannerUrl: [{ url: res.bannerUrl as string }]
        } as ProductType;
        form.setFieldsValue(newData);
      });
    } else {
      form.resetFields([]);
    }
    return () => {
      form.resetFields([]);
    };
  }, [id]);

  const onSubmitHandler = async () => {
    const values = (await form.validateFields()) as ProductType;
    const newValue = {
      ...values,
      cover: values.cover[0].url as string,
      bannerUrl: values.bannerUrl[0].url as string,
      originPrice: parseInt(values.originPrice as string),
      limitBuyNum: parseInt(values.limitBuyNum as string),
      preferentialPrice: parseInt(values.preferentialPrice as string),
      stock: parseInt(values.stock as string),
      type: values.type
    };
    if (values) {
      edit(id as string, newValue, close).catch(() => {
        void message.error("请检查表单！");
      });
    } else {
      void message.error("请检查表单！");
    }
  };

  return (
    <Drawer
      onClose={() => {
        close(false);
        form.resetFields([]);
      }}
      open={open}
      title={id ? "编辑商品" : "新建商品"}
      width="50vw"
      forceRender
      extra={
        <Space>
          <Button
            onClick={() => {
              close(false);
              form.resetFields([]);
            }}
          >
            取消
          </Button>
          <Button
            loading={editLoading as boolean}
            onClick={onSubmitHandler}
            type="primary"
          >
            提交
          </Button>
        </Space>
      }
    >
      <Spin spinning={loading as boolean}>
        <Form form={form} layout="vertical" scrollToFirstError preserve={false}>
          <Row className="row" gutter={20}>
            <Col span={12}>
              <Form.Item
                style={{ width: "100%" }}
                label="封面"
                name="cover"
                rules={[{ required: true }]}
                shouldUpdate
              >
                <UploadV2
                  label="替换封面"
                  id={id}
                  imgCropAspect={16 / 9}
                  maxCount={1}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                style={{ width: "100%" }}
                label="横幅"
                name="bannerUrl"
                rules={[{ required: true }]}
                shouldUpdate
              >
                <UploadV2
                  label="替换横幅"
                  id={id}
                  imgCropAspect={16 / 9}
                  maxCount={1}
                />
              </Form.Item>
            </Col>
          </Row>
          <Row className="row" gutter={30}>
            <Col span={10}>
              <Form.Item
                label="名称"
                name="name"
                rules={[
                  {
                    required: true
                  }
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={14}>
              <Form.Item label="描述" name="desc">
                <TextArea rows={5} showCount maxLength={200} />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={30}>
            <Col span={8}>
              <Form.Item
                label="原价"
                name="originPrice"
                style={{ width: "50%" }}
                rules={[
                  {
                    required: true
                  }
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="优惠后价格"
                name="preferentialPrice"
                style={{ width: "50%" }}
                rules={[
                  {
                    required: true
                  }
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="分类"
                name="type"
                style={{ width: "50%" }}
                rules={[
                  {
                    required: true
                  }
                ]}
              >
                <Select
                  showSearch
                  placeholder="选择分类"
                  optionFilterProp="children"
                  // onChange={onChange}
                  // onSearch={onSearch}
                  filterOption={(input, option) =>
                    (option?.label ?? "")
                      .toLowerCase()
                      .includes(input.toLowerCase())
                  }
                  options={product_arr.map((item) => ({
                    value: item.key,
                    label: item.title
                  }))}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="库存总额"
                name="stock"
                rules={[
                  {
                    required: true
                  }
                ]}
              >
                <InputNumber />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="每人限购数量"
                name="limitBuyNum"
                rules={[
                  {
                    required: true
                  }
                ]}
              >
                <InputNumber />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Spin>
    </Drawer>
  );
});

export default Edit;
